<template>
  <div class="app-container">
    <el-card class="box-card" v-if="detailVisible === false">
      <div slot="header" class="clearfix">
        <el-row>
          <el-button type="success" @click="handleCreate">
            &emsp;新增&emsp;
          </el-button>
          <el-button type="danger" @click="handleDeleteAll">批量删除</el-button>
          <el-form
            :inline="true"
            :model="listQuery"
            ref="listQuery"
            class="demo-form-inline"
          >
            <el-form-item label="">
              <el-date-picker
                v-model="listQuery.date"
                type="daterange"
                range-separator="至"
                value-format="timestamp"
                start-placeholder="开始日期"
                end-placeholder="结束日期"
              >
              </el-date-picker>
            </el-form-item>

            <el-form-item label="">
              <el-input
                type="text"
                v-model="listQuery.id"
                placeholder="请输入期数ID"
              ></el-input>
            </el-form-item>
            <el-form-item>
              <el-button type="primary" @click="searchSubmit">查询</el-button>
              <el-button type="primary" @click="resetSubmit">重置</el-button>
            </el-form-item>
          </el-form>
        </el-row>
      </div>
      <div class="item" v-loading="listLoading">
        <el-table
          ref="dataList"
          :data="menuList"
          @selection-change="handleSelectionChange"
          style="width:100%;margin-bottom: 20px;"
          row-key="id"
          border
          :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
        >
          <el-table-column type="selection"></el-table-column>
          <el-table-column prop="id" label="期数ID"> </el-table-column>
          <el-table-column prop="start_time" label="开始日期">
          </el-table-column>
          <el-table-column prop="end_time" label="结束日期"> </el-table-column>
          <el-table-column prop="status" label="状态">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.status === 1" type="success"
                >已完成</el-tag
              >
              <el-tag v-if="scope.row.status === 2" type="primary"
                >进行中</el-tag
              >
              <el-tag v-if="scope.row.status === 3" type="danger"
                >未开始</el-tag
              >
            </template>
          </el-table-column>
          <el-table-column prop="" label="周星礼物一" width="200">
            <template slot-scope="scope">
              <div>
                <el-tag
                  v-if="
                    scope.row.gift_data1 !== null &&
                      scope.row.gift_data1 !== '' &&
                      scope.row.gift_data1 !== undefined
                  "
                  type="warning"
                  style="margin:0 5px"
                  >{{ scope.row.gift_data1.name }}</el-tag
                >
                <el-tag
                  v-if="
                    scope.row.gift_data2 !== null &&
                      scope.row.gift_data2 !== '' &&
                      scope.row.gift_data2 !== undefined
                  "
                  type="warning"
                  style="margin:0 5px"
                  >{{ scope.row.gift_data2.name }}</el-tag
                >
              </div>
            </template>
          </el-table-column>
          <el-table-column prop="period" label="期数"> </el-table-column>
          <el-table-column prop="room_types" label="房间类型">
            <template slot-scope="scope">
              <div
                style="display:flex;flex-direction:column;justify-content:space-around"
              >
                <el-tag
                  type="info"
                  class="mb-2"
                  v-for="(item, index) in scope.row.room_types"
                  :key="'类型' + index"
                >
                  {{ item.room_type_name }}
                </el-tag>
              </div>
            </template>
          </el-table-column>

          <el-table-column label="操作" width="270px">
            <template slot-scope="scope">
              <el-button
                type="primary"
                size="mini"
                icon="el-icon-edit"
                @click="handleUpdate(scope.row)"
                plain
                >编辑</el-button
              >
              <el-button
                type="primary"
                size="mini"
                @click="handleDetail(scope.row)"
                plain
                >查看详情</el-button
              >
              <el-button
                type="danger"
                size="mini"
                icon="el-icon-delete"
                @click="handleDelete(scope.row)"
                plain
                >删除</el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <cus-pagination
          :total="total"
          :page.sync="listQuery.page"
          :limit.sync="listQuery.perPage"
          @pagination="getList"
        />
      </div>
    </el-card>
    <!-- 删除弹框 -->
    <el-dialog
      title="确定删除吗?"
      :visible.sync="deleteDialogVisible"
      width="435px"
    >
      <span style=""
        ><em style="font-style:normal;color:red">删除后不可恢复</em
        >，你还要继续吗？</span
      >
      <span slot="footer" class="dialog-footer">
        <el-button @click="deleteDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmDelete">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 新增编辑弹框 -->
    <el-dialog
      v-dialogDrag
      :title="titleMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
      @close="handleDialogClose('editRulesForm')"
    >
      <el-form
        :model="editRulesForm"
        :rules="editRulesFormRules"
        ref="editRulesForm"
        label-width="120px"
        class="demo-ruleForm"
      >
        <el-form-item label="周星日期" prop="weeks">
          <el-date-picker
            v-model="editRulesForm.weeks"
            type="week"
            format="yyyy 第 WW 周"
            value-format="yyyy-MM-dd"
            :picker-options="{ firstDayOfWeek: 1 }"
            placeholder="选择周"
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item label="周星礼物一" prop="gift_id_1">
          <el-select
            filterable
            v-model="editRulesForm.gift_id_1"
            clearable
            placeholder="请选择"
          >
            <el-option
              v-for="item in giftOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="周星礼物二" prop="gift_id_2">
          <el-select
            filterable
            v-model="editRulesForm.gift_id_2"
            clearable
            placeholder="请选择"
          >
            <el-option
              v-for="item in giftOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="期数" prop="period">
          <el-input-number
            v-model="editRulesForm.period"
            :min="1"
          ></el-input-number>
        </el-form-item>
        <el-form-item label="房间类型" prop="room_types">
          <el-select
            filterable
            multiple
            v-model="editRulesForm.room_types"
            clearable
            placeholder="请选择"
          >
            <el-option
              v-for="item in typeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item>
          <el-button @click="dialogFormVisible = false">返回</el-button>
          <el-button type="primary" @click="submitForm('editRulesForm')"
            >提交</el-button
          >
        </el-form-item>
      </el-form>
    </el-dialog>

    <el-card class="box-card" v-if="detailVisible">
      <div slot="header" class="clearfix">
        <el-row style="margin-bottom:20px">
          <el-button type="primary" @click="detailVisible = false"
            >&emsp;返回&emsp;</el-button
          >
        </el-row>
      </div>
      <div class="item" v-loading="listLoading">
        <el-row>
          <el-col :span="8">
            <p>期数ID：{{ detailList.id }}</p>
          </el-col>
          <el-col :span="8">
            <p>期数：{{ detailList.period }}</p>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8"
            ><p>开始日期：{{ detailList.start_time }}</p></el-col
          >
          <el-col :span="8"
            ><p>结束日期：{{ detailList.end_time }}</p></el-col
          >
        </el-row>
        <el-row>
          <el-col :span="8"
            ><p>
              状态：{{ detailList.status == 1 ? "已完成" : "进行中" }}
            </p></el-col
          >
          <el-col :span="10">
            <p>
              周星礼物：<el-tag type="warning" style="margin-right:10px">{{
                detailList.gift_data1.name
              }}</el-tag
              ><el-tag type="warning">{{ detailList.gift_data2.name }}</el-tag>
            </p>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="8">
            <ul>
              <li
                style="margin-bottom:20px"
                v-for="(item, index) in detailList.starList"
                :key="'周星' + index"
              >
                周星榜第{{ index + 1 }}名：{{
                  item.user_data ? item.user_data.nickname : ""
                }}
              </li>
            </ul>
          </el-col>
          <el-col :span="8">
            <ul>
              <li
                style="margin-bottom:20px"
                v-for="(item, index) in detailList.wealthList"
                :key="'富豪' + index"
              >
                富豪榜第{{ index + 1 }}名：{{
                  item.user_data ? item.user_data.nickname : ""
                }}
              </li>
            </ul>
          </el-col>
          <el-col :span="8">
            <ul>
              <li
                style="margin-bottom:20px"
                v-for="(item, index) in detailList.roomList"
                :key="'房间' + index"
              >
                房间榜第{{ index + 1 }}名：{{
                  item.user_data ? item.user_data.nickname : ""
                }}
              </li>
            </ul>
          </el-col>
        </el-row>
      </div>
    </el-card>
  </div>
</template>

<script>
import {
  listData,
  listGiftData,
  listRoomTypeData,
  putData,
  listDetailData,
  deleteData
} from "@/api/starWeek/starGift";
export default {
  data() {
    return {
      typeOptions: [],
      giftOptions: [],

      detailList: undefined,

      detailVisible: false,

      // 公告状态
      noticeStatus: [
        { value: 1, label: "开启" },
        { value: 2, label: "隐藏" }
      ],
      // 要修改的当前行的idsearchSubmit
      row_id: 0,
      // 表单规则
      editRulesFormRules: {
        weeks: [{ required: true, message: "请选择日期", trigger: "change" }],
        // gift_id_1:[{required: true, message: '请选择礼物', trigger: 'change' }],
        // gift_id_2:[{required: true, message: '请选择礼物', trigger: 'change' }],
        period: [{ required: true, message: "请输入期数", trigger: "change" }]
      },
      editRulesForm: {
        weeks: undefined,
        gift_id_1: undefined,
        gift_id_2: undefined,
        room_types: undefined,
        period: 1
      },
      dialogStatus: "",
      // dialog的头部信息
      titleMap: {
        update: "编辑",
        create: "新增"
      },
      dialogFormVisible: false,
      deleteDialogVisible: false,
      listLoading: false,
      menuList: [],
      limitList: [],
      listQuery: {
        page: 1,
        perPage: 10,
        id: undefined,
        date: undefined
      },
      total: 0,
      // 勾选内容
      multipleSelection: [],
      // 要删除的内容的ids
      dataIds: ""
    };
  },
  created() {
    this.getList();
    this.getGiftList();
    this.getRoomTypeList();
  },
  methods: {
    handleRelease(row) {
      this.row_id = row.id;
      putRelease(this.row_id).then(response => {
        if (response.code === 200) {
          this.getList();
          this.dialogFormVisible = false;
          this.$notify({
            type: "success",
            message: "操作成功",
            position: "bottom-right",
            showClose: false,
            duration: 3000
          });
        } else {
          this.$message({
            message: response.message,
            type: "error"
          });
        }
      });
    },
    getList() {
      this.listLoading = true;
      let urlData = "?";
      if (this.listQuery.page) {
        urlData = urlData + `page=${this.listQuery.page}&`;
      }
      if (this.listQuery.perPage) {
        urlData = urlData + `perPage=${this.listQuery.perPage}`;
      }
      if (this.listQuery.id) {
        urlData = urlData + `&id=${this.listQuery.id}`;
      }
      if (this.listQuery.date) {
        urlData =
          urlData + `&start_at=${Math.floor(this.listQuery.date[0] / 1000)}`;
        urlData =
          urlData + `&end_at=${Math.floor(this.listQuery.date[1] / 1000)}`;
      }

      listData(urlData).then(response => {
        this.menuList = response.data.data;
        this.total = response.data.total;
        this.listLoading = false;
      });
    },
    getGiftList() {
      let obj = {
        page: 1,
        perPage: 10000000
      };
      listGiftData(obj).then(response => {
        response.data.list.forEach(item => {
          this.giftOptions.push({ value: item.id, label: item.name });
        });
      });
    },
    getRoomTypeList() {
      listRoomTypeData().then(response => {
        response.data.list.forEach(item => {
          this.typeOptions.push({ value: item.id, label: item.type_name });
        });
      });
    },

    searchSubmit() {
      this.listQuery.page = 1;
      this.getList();
    },
    resetSubmit() {
      this.listQuery.page = 1;
      this.listQuery.perpage = 10;
      this.listQuery.date = undefined;
      this.listQuery.id = undefined;
    },
    // 点击新增
    handleCreate() {
      this.resetForm("editRulesForm");
      this.dialogStatus = "create";
      this.dialogFormVisible = true;
    },
    // 点击编辑
    handleUpdate(row) {
      this.row_id = row.id;
      let arr = [];
      this.editRulesForm.weeks = row.start_time;
      this.editRulesForm.gift_id_1 = row.gift_id_1;
      this.editRulesForm.gift_id_2 = row.gift_id_2;
      row.room_types.forEach(item => {
        arr.push(item.id);
      });
      this.editRulesForm.room_types = arr;
      this.editRulesForm.period = row.period;
      this.dialogStatus = "update";
      this.dialogFormVisible = true;
    },

    // 重置表单内容
    resetForm(formName) {
      this.$nextTick(() => {
        // this.$refs[formName].resetFields();
        if (this.$refs[formName] !== undefined) {
          this.$refs[formName].resetFields();
        }
        this.cityList = [];
        this.editRulesForm = {
          weeks: undefined,
          gift_id_1: undefined,
          gift_id_2: undefined,
          room_types: undefined,
          period: 1
        };
      });
    },
    submitForm(formName) {
      this.$refs[formName].validate(valid => {
        if (valid) {
          if (this.dialogStatus === "create") {
            let obj = JSON.parse(JSON.stringify(this.editRulesForm));
            let time = new Date(obj.weeks).getTime() / 1000;
            obj.weeks = time;
            obj.id = 0;
            obj.room_types = obj.room_types.join(",");
            putData(obj).then(response => {
              if (response.code === 200) {
                this.getList();
                this.dialogFormVisible = false;
                this.$notify({
                  type: "success",
                  message: "操作成功",
                  position: "bottom-right",
                  showClose: false,
                  duration: 3000
                });
              } else {
                this.$message({
                  message: response.message,
                  type: "error"
                });
              }
            });
          } else {
            let obj = JSON.parse(JSON.stringify(this.editRulesForm));
            let time = new Date(obj.weeks).getTime() / 1000;
            obj.weeks = time;
            obj.id = this.row_id;
            obj.room_types = obj.room_types.join(",");
            putData(obj).then(response => {
              if (response.code === 200) {
                this.getList();
                this.dialogFormVisible = false;
                this.$notify({
                  type: "success",
                  message: "操作成功",
                  position: "bottom-right",
                  showClose: false,
                  duration: 3000
                });
              } else {
                this.$message({
                  message: response.message,
                  type: "error"
                });
              }
            });
          }
        } else {
          return false;
        }
      });
    },
    handleDetail(row) {
      let obj = {};
      obj.id = row.id;
      obj.period = row.period;
      obj.start_time = row.start_time;
      obj.end_time = row.end_time;
      obj.gift_data1 = row.gift_data1;
      obj.gift_data2 = row.gift_data2;

      let urlData = `?week_id=${row.id}`;
      listDetailData(urlData).then(response => {
        obj.starList = response.data[1];
        obj.wealthList = response.data[2];
        obj.roomList = response.data[3];

        this.detailList = JSON.parse(JSON.stringify(obj));
        this.detailVisible = true;
      });
    },
    // 勾选
    handleSelectionChange(val) {
      this.multipleSelection = val;
    },
    // 点击单个删除
    handleDelete(row) {
      this.dataIds = { ids: [row.id] };
      this.deleteDialogVisible = true;
    },
    // 点击批量删除
    handleDeleteAll() {
      if (this.multipleSelection.length === 0) {
        this.$message({
          message: "请先勾选要删除的内容",
          type: "warning"
        });
        return;
      } else if (this.multipleSelection.length !== 0) {
        let ids = [];
        this.multipleSelection.forEach(item => {
          ids.push(item.id);
        });
        this.dataIds = { ids: ids };
      }
      this.deleteDialogVisible = true;
    },
    // 确定删除
    confirmDelete() {
      this.deleteDialogVisible = false;
      deleteData(this.dataIds).then(response => {
        if (response.code === 200) {
          this.getList();
          this.deleteDialogVisible = false;
          this.$notify({
            type: "success",
            message: "操作成功",
            position: "bottom-right",
            showClose: false,
            duration: 3000
          });
        } else {
          this.$message({
            message: response.message,
            type: "error"
          });
        }
      });
    },
    // 监听dialog关闭时的处理事件
    handleDialogClose(formName) {
      if (this.$refs[formName]) {
        this.$refs[formName].clearValidate(); // 清除整个表单的校验
      }
    }
  }
};
</script>

<style scoped>
[v-cloak] {
  display: none;
}
.clearfix:before,
.clearfix:after {
  display: table;
  content: "";
}
.clearfix:after {
  clear: both;
}

.box-card {
  width: 100%;
}

.demo-form-inline {
  float: right;
}

/deep/ .el-card__header {
  padding-bottom: 0;
}

/deep/.el-range-separator {
  width: 30px;
}

/deep/.el-table .cell {
  white-space: pre-wrap;
}
</style>
